package classfile

import "fmt"

type ClassFile struct {
	//Magic uint32	// 魔数
	MinorVersion uint16
	MajorVersion uint16
	Constantpool ConstantPool    // 常量池
	AccessFlags  uint16          // 类访问标志
	ThisClass    uint16          // 类索引
	SuperClass   uint16          // 超类索引
	Interfaces   []uint16        // 接口索引表
	Fields       []*MemberInfo   // 字段表
	Methods      []*MemberInfo   // 方法表
	Attributes   []AttributeInfo // 属性表
}

func Parse(classData []byte) (cf *ClassFile, err error) {
	defer func() {
		if r := recover(); r != nil {
			var ok bool
			err, ok = r.(error)
			if !ok {
				err = fmt.Errorf("%v", r)
			}
		}
	}()

	cr := &ClassReader{classData}
	cf = &ClassFile{}
	cf.Read(cr)
	return
}

func (self *ClassFile) ClassName() string {
	return self.Constantpool.getClassName(self.ThisClass)
}

func (self *ClassFile) SuperClassName() string {
	if self.SuperClass > 0 {
		return self.Constantpool.getClassName(self.SuperClass)
	}
	return ""
}

func (self *ClassFile) InterfaceNames() []string {
	if len(self.Interfaces) < 1 {
		return []string{}
	}
	interfaceNames := make([]string, len(self.Interfaces))
	for i, cpIndex := range self.Interfaces {
		interfaceNames[i] = self.Constantpool.getClassName(cpIndex)
	}
	return interfaceNames
}
